package com.examsystem.controller;

import com.alibaba.fastjson.JSON;
import com.examsystem.config.SftpConfig;
import com.examsystem.pojo.vo.*;
import com.examsystem.service.UserClassService;
import com.examsystem.util.RedisUtil;
import com.examsystem.util.UploadImgUtils;
import com.examsystem.service.UploadService;
import com.examsystem.pojo.User;
import com.examsystem.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import static com.examsystem.Const.ConstMsg.SET_CLASS_FAIL_MSG;


/**
 * @author fire'ge
 */
@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserClassService userClassService;
    @Resource
    private SftpConfig sftpConfig;

    @Value("${getImg.url}")
    String url;


    /*
    学生端代码
     */

    /**
     * 前端传入一个user的json对象进行封装，封装成功之后就进行登录验证
     * @param user 用于验证的user类
     * @return 返回验证的结果，如果验证通过则返回token
     */
    @ResponseBody
    @RequestMapping(value = "/user/studentLogin",produces = "application/json;charset=utf-8")
    public String studentLogin(@RequestBody User user) {
        Result login = userService.studentLogin(user);
        return JSON.toJSONString(login);
    }


    /**
     *  查询出用户的基本信息
     *
     * @return 返回好用户的基本信息
     */
    @ResponseBody
    @RequestMapping(value = "/user/getStudentUserMsg",produces = "application/json;charset=utf-8")
    public String getUserMsg() {
        LoginUser user = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int userId = user.getUser().getUserId();
        UserMsg userMsg = userService.getUserMsg(userId);
        userMsg.setPhotoUrl(url +userMsg.getPhotoUrl());
        return JSON.toJSONString(Result.succ(userMsg));
    }

    /**
     * 注销用户
     *
     * @return 返回好注销成功的信息
     */
    @ResponseBody
    @RequestMapping(value = "/user/logout",produces = "application/json;charset=utf-8")
    public String logout() {
        LoginUser user = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        redisUtil.del("login:user" + user.getUser().getUserId());
        return JSON.toJSONString(Result.succ(200,"注销成功",null));
    }

    /**
     *  上传图片
     * @param file 用户传输过来的照片文件
     * @return 返回上传是否成功的数据
     */
    @ResponseBody
    @RequestMapping(value = "/user/uploadImg")
    public String uploadImg(@RequestParam("imgFile") MultipartFile file) {
        LoginUser user = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String fileName = userService.uploadImages(sftpConfig, file, user.getUser().getUserId());
        userService.updateUserImg(user.getUser().getUserId(),fileName);
        return JSON.toJSONString(Result.succ("上传数据成功"));
    }

    /**
     * 获取该学生在该班的科任老师的信息
     * @return 返回学生在该班的科任老师的信息
     */
    @ResponseBody
    @RequestMapping(value = "/user/getTeacherMsg")
    public String getStudentsTeacherMsg() {
        LoginUser user = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<StuTeacherMsg> teacherMsg = userService.queryTeacherMsg(user.getUser().getUserId());
        return JSON.toJSONString(Result.succ(teacherMsg));
    }


    /**
     * 提供用户的注册功能
     * @param user 传入一个user对象，进行注册
     * @return 返回注册成功的信息
     */
    @ResponseBody
    @RequestMapping("/user/register")
    public String register(@RequestBody User user){
        User userByPhoneNum = userService.getUserByPhoneNum(user.getUserPhoneNum());
        if(userByPhoneNum==null){
            userService.addUser(user);

        }
        else {
            throw new RuntimeException("已注册");
        }
        return JSON.toJSONString(Result.succ("注册成功"));
    }

    @ResponseBody
    @RequestMapping("/user/setUserClass")
    public String setUserClass(@Param("classId") int classId){
        LoginUser user = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        userClassService.addUserClass(user.getUser().getUserId(),classId);
        return JSON.toJSONString(Result.succ(SET_CLASS_FAIL_MSG));
    }

    /*
    教师端
     */


    @Autowired
    private UploadService uploadService;


    /**
     * @param user 接收用户的信息
     * @return 返回登录成功信息
     */
    @RequestMapping("/user/teacherLogin")
    public String teacherLogin(@RequestBody User user){
        Result login = userService.teacherLogin(user);
        return JSON.toJSONString(login);
    }


    @PostMapping({"/userImg"})
    @ResponseBody
    public Result updateUserImg(@RequestParam("file") MultipartFile file,@AuthenticationPrincipal LoginUser user){
        UploadImgUtils uploadImgUtils = new UploadImgUtils();
        String imgPath = uploadImgUtils.uploadImg(file);
        int userId = user.getUser().getUserId();
        return uploadService.uploadImg(imgPath, userId);

    }

    /**
     *  查询出用户的基本信息
     * @param user @AuthenticationPrincipal注解来获取到token中的userId,查询封装成loginUser
     * @return 返回好用户的基本信息
     */
    @ResponseBody
    @RequestMapping(value = "/user/getUserMsg",produces = "application/json;charset=utf-8")
    public String getTeacherMsg(@AuthenticationPrincipal LoginUser user) {
        int teacherId = user.getUser().getUserId();
        User teacherMsg = userService.getTeacherMsg(teacherId);

//
//        teacherMsg.setPhotoUrl(url + userMsg.getPhotoUrl());
        return JSON.toJSONString(Result.succ(teacherMsg));
    }

    /**
     * 修改教师账号密码
     * @param password  密码
     * @param teacherId .
     * @return  result结果集对象
     */
    @RequestMapping("user/updateTeacher")
    @ResponseBody
    public Result updateTeacherPassword(@RequestParam("password") String password,@RequestParam("teacherId") Integer teacherId){
        return userService.updatePassword(teacherId, password);
    }

}
